import { DataSource } from 'typeorm';
import { Notification, NotificationType, SourceType } from '../../../entities/notification.entity';
import { User } from '../../../entities/user.entity';
import { Task } from '../../../entities/task.entity';
import { TaskComment } from '../../../entities/task-comment.entity';

/**
 * 通知数据初始化
 */
export class NotificationSeed {
  constructor(private dataSource: DataSource) {}

  /**
   * 执行种子初始化
   */
  async run(): Promise<void> {
    console.log('开始初始化通知数据...');
    const notificationRepository = this.dataSource.getRepository(Notification);
    const userRepository = this.dataSource.getRepository(User);
    const taskRepository = this.dataSource.getRepository(Task);
    const commentRepository = this.dataSource.getRepository(TaskComment);

    // 查找所有用户
    const adminUser = await userRepository.findOneBy({ username: 'admin' });
    const normalUser = await userRepository.findOneBy({ username: 'user' });
    const guestUser = await userRepository.findOneBy({ username: 'guest' });

    if (!adminUser || !normalUser || !guestUser) {
      console.log('未找到基础用户，跳过通知初始化');
      return;
    }

    // 查找一些任务和评论
    const tasks = await taskRepository.find({ 
      take: 3,
      order: { createdAt: 'DESC' }
    });
    
    if (tasks.length === 0) {
      console.log('未找到任务，跳过通知初始化');
      return;
    }

    const comments = await commentRepository.find({
      take: 2,
      order: { createdAt: 'DESC' }
    });

    if (comments.length === 0) {
      console.log('未找到评论，跳过通知初始化');
      return;
    }

    // 创建示例通知
    const notificationsData = [
      // 任务分配通知
      {
        title: '任务已分配给您',
        content: `您有一个新的任务需要处理：${tasks[0].title}`,
        type: NotificationType.TASK_ASSIGNMENT,
        userId: normalUser.id,
        sourceId: tasks[0].id,
        sourceType: SourceType.TASK,
        isRead: false,
      },
      {
        title: '任务已分配给您',
        content: `您有一个新的任务需要处理：${tasks[1] ? tasks[1].title : '任务开发'}`,
        type: NotificationType.TASK_ASSIGNMENT,
        userId: adminUser.id,
        sourceId: tasks[1] ? tasks[1].id : tasks[0].id,
        sourceType: SourceType.TASK,
        isRead: true,
      },
      
      // 任务评论通知
      {
        title: '您的任务有新评论',
        content: `您的任务"${tasks[0].title}"收到了新评论: ${comments[0].content.substring(0, 30)}...`,
        type: NotificationType.TASK_COMMENT,
        userId: normalUser.id,
        sourceId: comments[0].id,
        sourceType: SourceType.COMMENT,
        isRead: false,
      },
      
      // 评论回复通知
      {
        title: '您的评论收到了回复',
        content: `您在任务"${tasks[1] ? tasks[1].title : tasks[0].title}"的评论收到了回复: 问题已解决，可以继续开发`,
        type: NotificationType.COMMENT_REPLY,
        userId: adminUser.id,
        sourceId: comments[1] ? comments[1].id : comments[0].id,
        sourceType: SourceType.REPLY,
        isRead: false,
      },
      
      // 任务截止日期通知
      {
        title: '任务即将到期',
        content: `您负责的任务"${tasks[2] ? tasks[2].title : tasks[0].title}"将在明天到期，请尽快完成`,
        type: NotificationType.TASK_DUE_DATE,
        userId: guestUser.id,
        sourceId: tasks[2] ? tasks[2].id : tasks[0].id,
        sourceType: SourceType.TASK,
        isRead: false,
      }
    ];

    try {
      for (const notificationData of notificationsData) {
        const notification = notificationRepository.create(notificationData);
        await notificationRepository.save(notification);
        console.log(`创建通知: ${notification.title} (ID: ${notification.id})`);
      }
      console.log('通知数据初始化完成！');
    } catch (error) {
      console.error('通知数据初始化出错:', error.message);
    }
  }
} 